package org.example.demo4.service;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Base64;


import jakarta.annotation.Resource;
import org.example.demo4.exception.CaptchaException;
import org.example.demo4.exception.CaptchaExpireException;
import org.example.demo4.exception.ServiceException;
import org.example.demo4.exception.UserPasswordNotMatchException;
import org.example.demo4.model.SysDeptEntity;
import org.example.demo4.model.SysUserEntity;
import org.example.demo4.utils.*;
import org.example.demo4.utils.ip.IpUtils;
import org.example.demo4.utils.login.ExtsAuthenticationToken;
import org.example.demo4.utils.login.LoginUser;
import org.example.demo4.utils.login.TokenService;
import org.example.demo4.utils.sync.AsyncManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private SysUserService userService;

    @Autowired
    private SysConfigService configService;

    @Autowired
    private SysDeptService sysDeptService;
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    
    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff)
        {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 存放数据权限字段 sapCode
        SysDeptEntity dept = sysDeptService.getById(loginUser.getDeptId());
        if(dept != null) {
            loginUser.setSapCode(dept.getSapCode());
        }
        // 生成token
        return tokenService.createToken(loginUser);
    }
    
   	public static String decryBASE64(String key) throws Exception{
   		return new String(Base64.getDecoder().decode(key));
   	}

   	/***
   	 * BASE64加密
   	 * @param key
   	 * @return
   	 * @throws Exception
   	 */
   	public static String encryptBASE64(byte[] key) {
   		return Base64.getEncoder().encodeToString(key);
   	}
   	
   	public static void main(String[] args) throws Exception {
		String token = "ZD04094";
		System.out.println(token);
		// WkQwMjIyMQ%3D%3D
		System.out.println(encryptBASE64(token.getBytes("utf-8")));
		System.out.println(URLEncoder.encode("WkQwNDA5NA==","utf-8"));

		System.out.println(decryBASE64(encryptBASE64(token.getBytes())));
		
		System.out.println(decryBASE64(encryptBASE64(token.getBytes())));
		// WkQwNDA5NA%3D%3D
		System.out.println(decryBASE64("WkQwNDA5NA%3D%3D"));
		System.out.println(decryBASE64("WkQwNDA5NA%3D%3D"));
		
		System.out.println(decryBASE64(URLDecoder.decode("WkQwNDA5NA%3D%3D","utf-8")));
		

	}

   	
    public String extLogin(String accessToken)
    {
    	logger.info("单点请求参数："+accessToken);
        // 用户验证
        Authentication authentication = null;
        String username =accessToken;
        try
        {
            username=decryBASE64(accessToken);
        	logger.info("单点请求参数解密："+accessToken);

            authentication = authenticationManager
                    .authenticate(new ExtsAuthenticationToken(username));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }
    

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUserEntity sysUser = new SysUserEntity();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
